import { Button, Table, Switch, message, Popconfirm } from "antd";
import React, { useState, useEffect } from "react";
import cssModule from "@/views/system/role/role.module.scss";
import { Role } from "@/types";
import {
    getRoleListByPage,
    addRole,
    updateRole,
    getRoleById,
    deleteRoleById,
} from "@/api";
import RoleFormModal from "./roleForm";
import RoleSearch from "./searchFrom";
import usePageOption from "../../../hooks/usePageOption";
const RolePage: React.FC = () => {
    const columns = [
        {
            title: "角色编码",
            dataIndex: "roleName",
            key: "roleName",
            width: "100px",
        },
        {
            title: "角色名称",
            dataIndex: "roleDesc",
            key: "roleDesc",
            width: "150px",
        },
        {
            title: "角色状态",
            dataIndex: "dataStatus",
            key: "dataStatus",
            width: "100px",
            render(dataStatus: boolean, row: Role) {
                return (
                    <Switch
                        checkedChildren="启用"
                        defaultChecked={dataStatus}
                        unCheckedChildren="禁用"
                        onChange={v => {
                            changeDataStatus(row, v);
                        }}
                    />
                );
            },
        },
        {
            title: "角色创建时间",
            dataIndex: "createTime",
            key: "createTime",
        },
        {
            title: "角色更新时间",
            dataIndex: "updateTime",
            key: "updateTime",
        },
        {
            title: "操作",
            key: "handle",
            width: "200px",
            render(row: Role) {
                return (
                    <>
                        <Button
                            type="link"
                            size="small"
                            onClick={() => {
                                editRoleHandler(row);
                            }}
                        >
                            编辑
                        </Button>
                        <Popconfirm
                            title="是否要删除当前角色"
                            onConfirm={() => deleteRole(row.id)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="link" size="small">
                                删除
                            </Button>
                        </Popconfirm>
                    </>
                );
            },
        },
    ];
    const [roleList, setRoleList] = useState<Role[]>([]);
    const [loading, setLoading] = useState(false);
    const [searchForm, setSearchForm] = useState({});
    const getRoleList = () => {
        setLoading(true);
        getRoleListByPage({ ...searchForm, page: 1, pageSize: 10 }).then(
            res => {
                res.data.list.forEach(d => {
                    d.dataStatus = (d.dataStatus as any) === 1;
                });
                setRoleList(res.data.list);
                setPageOption({ ...pageOption, total: res.data.total });
                setLoading(false);
            }
        );
    };
    const [pageConfig, setPageConfig] = useState({ page: 1, pageSize: 10 });
    const [pageOption, setPageOption] = usePageOption((page, pageSize) => {
        setPageConfig({
            page,
            pageSize: pageSize ? pageSize : pageConfig.pageSize,
        });
    });
    const [visible, setVisible] = useState(false);
    const [editRole, setEditRole] = useState<Role>();
    const resetSubmit = () => {
        setVisible(false);
        setEditRole(undefined);
        getRoleList();
        flag = false;
    };
    let flag = false;
    const submit = (values: any) => {
        if (flag) {
            return;
        }
        flag = true;
        if (!editRole) {
            addRole(values)
                .then(res => {
                    message.success("添加角色成功");
                    resetSubmit();
                })
                .catch(e => {
                    flag = false;
                });
        } else {
            values.id = editRole.id;
            updateRole(values)
                .then(() => {
                    message.success("修改角色成功");
                    resetSubmit();
                })
                .catch(() => {
                    flag = false;
                });
        }
    };
    const deleteRole = (id: number) => {
        deleteRoleById(id)
            .then(() => {
                message.success("删除成功");
                getRoleList();
                return;
            })
            .catch(() => {
                message.success(`删除失败`);
                getRoleList();
            });
    };
    const changeDataStatus = (row: Role, val: boolean) => {
        getRoleById(row.id).then(res => {
            const role = res.data;
            role.dataStatus = (val ? 1 : 0) as any;
            updateRole(role as any).then(() => {
                message.success("更新成功");
                getRoleList();
            });
        });
    };
    const editRoleHandler = (row: Role) => {
        getRoleById(row.id).then(res => {
            const role = res.data;
            setEditRole(role);
            setVisible(true);
        });
    };
    const onSearch = (form: any) => {
        setSearchForm(form);
        setPageConfig({ ...pageConfig, page: 1 });
    };
    const onReset = () => {
        setSearchForm({});
        setPageConfig({ ...pageConfig, page: 1 });
    };
    useEffect(() => {
        getRoleList();
    }, [pageConfig]);
    useEffect(() => {
        getRoleList();
    }, []);
    return (
        <div className={cssModule.roleContainer}>
            <RoleSearch onSearch={onSearch} onRest={onReset} />
            <div className={cssModule.btnWrap}>
                <Button onClick={() => setVisible(true)}>新建</Button>
            </div>
            <div className="table-wrap">
                <Table
                    bordered
                    loading={loading}
                    columns={columns}
                    rowKey="id"
                    dataSource={roleList}
                    pagination={pageOption}
                ></Table>
            </div>
            <RoleFormModal
                visible={visible}
                submit={submit}
                onCancel={() => setVisible(false)}
                editRole={editRole}
            ></RoleFormModal>
        </div>
    );
};
export default RolePage;
